import fs from '@ohos.file.fs';
import hilog from '@ohos.hilog';
import { globalData } from './globalData';
import { isEmpty, showPopup } from './utils';
import { XLog, LogLevel, OhPrinter, FilePrinter, LogConfiguration, DateFileNameGenerator, FileSizeBackupStrategy, FileLastModifiedCleanStrategy, ConsolePrinter } from '@ohos-port/xlog-ts';

export class logger {
  private prefix: string;
  private readonly domain: number;
  private readonly format: string = '%{public}s, %{public}s';

  private static _instance: logger;

  static get instance(): logger {
    if (this._instance == null)
      this._instance = new logger();
    return this._instance;
  }

  private constructor() {
    this.domain = 0xFF00;
  }

  private init() {
    try {
      if (isEmpty(this.prefix)) {
        this.prefix = 'ddf_ohos';
        let config = new LogConfiguration.Builder()
          .setTag(this.prefix)
          .setLogLevel(LogLevel.ALl)
          .build();
        let printer = new FilePrinter.Builder(globalData.logDir)
          .setFileNameGenerator(new DateFileNameGenerator())
          .setBackupStrategy(new FileSizeBackupStrategy(5 * 1024 * 1024))
          .setCleanStrategy(new FileLastModifiedCleanStrategy(7 * 24 * 60 * 60 * 1000))
          .build();
        XLog.init(config, [printer, new OhPrinter(), new ConsolePrinter()]);
      }
    } catch (e) {
      hilog.error(this.domain, this.prefix, this.format, e);
    }
  }

  info(msg: string, show?: boolean) {
    try {
      this.init();
      hilog.info(this.domain, this.prefix, this.format, msg);
      XLog.i(msg);
      if (show)
        showPopup('发生错误：' + msg);
    } catch (e) {
      console.log(e);
    }
  }

  error(e: Error | string, show?: boolean) {
    try {
      this.init();
      let msg = typeof e === 'string' ? e : `error message:${e?.message} / stack:${e?.stack}`;
      hilog.error(this.domain, this.prefix, this.format, msg);
      XLog.e(msg);
      if (show)
        showPopup('发生错误：' + msg);
    } catch (e) {
      console.log(e);
    }
  }

  clear() {
    try {
      fs.rmdir(globalData.logDir);
      fs.mkdir(globalData.logDir);
      this.init();
    } catch (e) {
      console.log(e);
    }
  }
}